#include "CConfigFile.h"
#include "CTokenSplitter.h"

#include "g_mem.h"
#include <stdio.h>

CConfigFile::CConfigFile()
{
	m_numValues = 0;
	m_maxValues = 10;
	
	g_allocv(m_keys, char*, m_maxValues);
	g_allocv(m_values, double, m_maxValues);
	
	m_lastFile = NULL;
}

void CConfigFile::releaseData()
{
	for (int i = 0; i < m_numValues; i++)
		g_free(m_keys[i]);
	
	g_free(m_keys);
	g_free(m_values);
	
	m_numValues = 0;
	m_maxValues = 0;
}

CConfigFile::~CConfigFile()
{
	g_free(m_lastFile);
	releaseData();
}

int CConfigFile::readConfig(const char *file)
{
	g_free(m_lastFile);
	g_strdup(m_lastFile, file);

	FILE *f = fopen(file, "rt");
	if (!f)
		return 1;

	CTokenSplitter *ts = new CTokenSplitter();

	char s[1024];
	
	while (fgets(s, 1024, f))
	{
		int n = ts->split(s);
		
		if (n == 2)
		{
			setValue(ts->getToken(0), strtod(ts->getToken(1), NULL));
			//			setValue(ts->getToken(0), 0);
		}
	}
	fclose(f);
	
	delete ts;
	return 0;
}

int CConfigFile::writeConfig(const char *file)
{
	g_free(m_lastFile);
	g_strdup(m_lastFile, file);
	
	FILE *f = fopen(file, "wt");
	if (!f)
		return 1;
	
	for (int i = 0; i < m_numValues; i++)
		fprintf(f, "%s\t\t%.5g\n", m_keys[i], m_values[i]);
	
	fclose(f);
	
	return 0;
}

int CConfigFile::findKey(const char *key)
{
	for (int i = 0; i < m_numValues; i++)
		if (!g_strcmp(key, m_keys[i]))
			return i;
		
		return -1;
}

double CConfigFile::getValue(const char *name)
{
	int p =findKey(name);
	if (p >= 0)
		return m_values[p];
	
	return 0;
}

void CConfigFile::setValue(const char *name, double value)
{
	setValue(name, value, 1);
}

void CConfigFile::setValue(const char *name, double value, int now)
{
	int p = findKey(name);
	
	if (p < 0)
	{
		if (m_numValues >= m_maxValues)
		{
			char **newKeys;
			double *newValues;
			int newMax = m_maxValues +(m_maxValues + 1)/2;
			int newNum = m_numValues;
			
			g_allocv(newKeys, char*, newMax);
			g_allocv(newValues, double, newMax);
			
			for (int i = 0; i < m_maxValues; i++)
			{
				newKeys[i] = m_keys[i];
				m_keys[i] = NULL;
				newValues[i] = m_values[i];
			}
			
			releaseData();
			
			m_keys = newKeys;
			m_values = newValues;
			m_numValues = newNum;
			m_maxValues = newMax;
		}
		
		p = m_numValues++;
		g_strdup(m_keys[p], name);
	}
	
	m_values[p] = value;
}

